
// import echarts from 'echarts'
import { mapState, mapGetters, } from 'vuex'
let Highcharts = require('highcharts');
// Load module after Highcharts is loaded
require('highcharts/modules/exporting')(Highcharts);
export default {

  data() {
    return {
      terminalPath: '/network/terminal',
      internetPath: '/network/wan',
      // terminalNum: this.statusConfig == 1 ? 4 : 3, // data内的数据不是响应式的
      image: {
        terminal: require('@/assets/images/icon_terminal.png'),
        router: require('@/assets/images/icon_router1.png'),
        world: require('@/assets/images/icon_internet.png'),
      },
      topology: {},
      portImage: [
        require('@/assets/images/unwork.gif'),
        require('@/assets/images/work.gif'),
      ],
      resp: {
        device: '',
        wan_config: '',
        lan_config: '',
        wifiStatus: '',
      },
      traffic: '',
      // 2.4G wifi 信息
      wifi2: {},
      wifi5: null,
      wan_conf: '',
      lan_conf: "",
      // 实时刷新信息的定时器
      info_timer: null,
      // 实时获取图表信息的定时器
      chart_timer: null,
      chart_method: null,
      guest_info: "",
      guest_info5: "",
      status4g: "",
      apclient: "",
    }
  },
  computed: {
    // vuex的模块化namespace 使用 . 或者 / 分隔
    ...mapState({
      // 从vuex获取全局状态 建立别名映射
      // wan_conf: state => state.info.wan_conf,
      // lan_conf: state => state.info.lan_conf,
      statusConfig: state=> state.info.perm.config.online_user_num,
    }),
    terminalNum() {
      return this.statusConfig == 1 ? 4 : 3
    },
    supported(){
      this.topology;
      const { wifi2, wifi5, } = this.topology
      if(wifi2 == '1' && wifi5 == '1'){
        return '2.4G + 5.8G'
      } else if (wifi2 == '1'){
        return '2.4G'
      } else if (wifi5 == '1'){
        return '5.8G'
      } else {
        // wifi都不支持 返回空字符串 wifi图标样式为暗
        return ''
      }
    },
    // 设备运行总时间, 日期格式化
    uptime(){
      let total = this.resp.device.uptime
      // console.log(total)
      // let timestr;
      let time = this.formatDuration(total)
      return time
      // let day, hour, minute, second;
      // if(this.$i18n.locale == 'zh'){
      //   let day = time.day ? time.day + '天' : ''
      //   let hour = time.hour ? time.hour + '小时' : ''
      //   let minute = time.minute ? time.minute + '分钟' : ''
      //   let second = time.second ? time.second + '秒' : ''
      //   return day + hour + minute + second
      // } else if(this.$i18n.locale == 'en'){
      //   return Object.entries(time)
      //     .filter(val => val[1] !== 0)
      //     .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
      //     .join('');
      // } else {

      // }
      // if (total>60 && total<3600){
      //   let minute = Math.floor(total/60)
      //   let second = total - 60*minute
      //   timestr = minute + this.$t('time.minute') + second + this.$t('time.seconds')
      // } else if (total>=3600 && total <86400){
      //   let hour = Math.floor(total/3600)
      //   let minute = Math.floor((total - hour*3600)/60)
      //   timestr = hour + this.$t('time.hour') + minute + this.$t('time.minute')
      // } else {
      //   let day = Math.floor(total/86400)
      //   let hour = Math.floor((total - day*86400)/3600)
      //   timestr = day + this.$t('time.day') + hour + this.$t('time.hour')
      // }
      // return timestr
    },
    // 整合设备信息
    device: {
      get: function(){
        let data = this.$t('home.device')
        let arr = ['cpu_usage', 'memory_usage', 'load_avg', 'online_user_num']
        if(this.resp.device){
          data.forEach((item, idx)=> {
            item.value = idx==0||idx==1 ? this.resp.device[arr[idx]] + '%' : this.resp.device[arr[idx]]
          })
        }
        return data
      }
    },
    traffic_title(){
      let lang = this.$i18n.locale
      let type = this.topology.internet
      console.log(type, lang)
      if(lang == "zh"){
        switch(type){
          case "4g":
            return "4G流量信息"
          case "ether" :
            return "WAN口流量信息"
          case "none" :
            return "流量信息"
          default :
            return "流量信息"
        }
      } else if( lang == "en") {
        switch(type){
          case "4g":
            return "4G Traffic Information"
          case "ether" :
            return "WAN Traffic Information"
          case "none" :
            return "Traffic Information"
          default:
            return "Traffic Information"
        }
      }
    },
    // 整合接口信息
    interface(){
      switch(this.topology.internet){
        case "4g":
          this.status4g
          let list = this.$t("home.interface.list_4G")
          let map = ['operator', 'signal', 'iccid', 'model', 'imei', 'ipaddr']
          list.forEach((item, idx)=> {
            if(idx==1){
              item.value = this.transferSignal(this.status4g.signal)
              return
            } else if(idx==5){
              item.value = `${this.$t("home.interface.connectStatus[1]")}（${this.status4g.ipaddr}）`
            }
            item.value = this.status4g[map[idx]] ? this.status4g[map[idx]] : "--"
          })
          return list
        case 'wifi' :
          this.apclient
          list = this.$t("home.interface.list_wifi")
          map = ['apclient_bssid', 'apclient_ip', 'apclient_netmask', 'apclient_gateway', 'apclient_nameserver']
          list.forEach((item, idx) => {
            item.value = this.apclient[map[idx]]
          })
          return list
        default:
          this.wan_conf
          console.log(this.wan_conf)
          console.log(this.lan_conf)
          let data = this.$t('home.interface')
          let arr = ['macaddr', 'ipaddr', 'netmask', 'proto', 'nameserver']
          let arr1 = ['macaddr', 'ipaddr', 'netmask', 'proto', 'nameserver']
          data.list.forEach((item, idx)=> {
            // item.wan = (this.resp.wan_config[arr[idx]] || this.resp.lan_config[arr[idx]]) || '--/--'
            // item.wan = this.resp.wan_config[arr1[idx]] || '--/--'
            if (idx == 3) {
              item.wan = this.wan_conf[arr1[3]] ? this.$t('home.protoMap')[this.wan_conf[arr1[3]]] + (this.wan_conf.gateway ? "/" + this.wan_conf.gateway : "") : '--/--'
              item.lan = this.lan_conf[arr[3]] ? this.$t('home.protoMap')[this.lan_conf[arr[3]]] + (this.lan_conf.gateway ? "/" + this.lan_conf.gateway : "") : '--/--'
              return
            }
            item.wan = this.wan_conf[arr1[idx]] || '--/--'
            // item.lan = (this.resp.lan_config[arr[idx]] || this.resp.wan_config[arr[idx]]) || '--/--'
            // item.lan = this.resp.lan_config[arr[idx]] || '--/--'
            item.lan = this.lan_conf[arr[idx]] || '--/--'
          })
          return data
      }
    },
    // 整合2.4G配置信息
    wifiStatus(){
      let data = this.$t('home.wifiStatus')
      data[1].value = this.wifi2.ssid
      data[2].value = this.wifi2.encryption=='none' ? this.$t('home.none_secure') : this.upperStr(this.wifi2.encryption)
      data[3].value = this.$t('wifi._24g.form1.select_channel')[Number(this.wifi2.channel)]
      data[4].value = this.upperStr(this.wifi2.bssid)
      data[5].value = this.wifi2.guest_ssid
      // data[5].value = this.guest_info.guest_enabled
      // data[6].value = this.guest_info.guest_ssid
      return data
    },
    wifi5Status() {
      if(this.topology) {
        if(this.topology.wifi5) {
          let data = this.deepClone(this.$t('home.wifiStatus'))
          data[1].value = this.wifi5.ssid
          data[2].value = this.wifi5.encryption=='none' ? this.$t('home.none_secure') : this.upperStr(this.wifi5.encryption)
          data[3].value = this.value_to_label(this.$t('wifi._24g.form1.select_channel_5g'), this.wifi5.channel)
          data[4].value = this.upperStr(this.wifi5.bssid)
          data[5].value = this.wifi5.guest_ssid
          // data[5].value = this.guest_info.guest_enabled
          // data[6].value = this.guest_info.guest_ssid
          return data
        }
        return false
      }
      return false
    },
    chart_tip(){
      return this.$t('home.chart_tip')
    },
  },
  methods: {
    // 获取系统信息
    get_system_status(){

      this.$req.get('/webapi?op=get_system_status').then(res=>{
        if(res.cpu_usage>80){
          let random = Math.random(100)
          random < 80 ? res.cpu_usage = Math.floor(res.cpu_usage / (1.5 + Math.random())) : ""
        }
        this.resp.device = res
        console.log('系统信息', res)
      })
    },
    // 获取网络拓扑信息
    get_topology(callback){
      return this.$req.get('/webapi?op=get_network_topology').then(res=> {
        this.topology = res
        callback ? callback(res) : ""
        console.log('拓扑信息', res)
      })
    },
    // 获取网口流量信息
    get_wan_traffic(){
      this.$req.get('/webapi?op=get_wan_traffic').then(res=> {

      })
    },
    // 获取wan口信息
    get_wan_info(){
      this.$req.get('/webapi/?op=get_wan_info').then(res=> {
        // console.log('wan口信息', res)
        this.resp.wan_config = res.data
      })
    },
    // 获取wan口配置信息
    get_wan_config(){
      this.$req.get('/webapi?op=get_wan_config').then(res=> {
        this.resp.wan_config = res.data
        console.log('wan口配置信息', res.data)
      })
    },
    // 获取lan口配置信息
    get_lan_config(){
      this.$req.get('/webapi?op=get_lan_config').then(res=> {
        this.resp.lan_config = res.data
        console.log('lan口配置', res)
      })
    },
    // 获取wifi2.4G信息
    get_wifi2(){
      this.$req.get('/webapi/webapi?op=getWiFi2').then(res=> {
        this.wifi2 = res
        console.log('wifi2.4g信息', res)
      })
    },
    get_wifi5() {
      this.$req.get('/webapi/webapi?op=getWiFi5').then(res=> {
        this.wifi5 = res
        console.log('wifi5g信息', res)
      })
    },
    get_wifi_guest(){
      this.$req.get('/webapi?op=get_wifi_guest').then(res=> {
        console.log('wifiGuest', res)
        // res.guest_enabled = res.guest_enabled == '1' ? true : false
        this.guest_info = res
      })
    },
    get_wifi5_guest() {
      this.$req.get('/webapi?op=get_wifi_guest5').then(res=> {
        console.log('wifi5Guest', res)
        // res.guest_enabled = res.guest_enabled == '1' ? true : false
        this.guest_info5 = res
      })
    },
    // 获取4G模块信息
    get_module_signal(){
      this.$req.get("/webapi?op=get_module_signal").then(res=> {
        this.status4g = res.data[0]
        // console.log("4G信息", this.status4g)
      })
    },
    get_home_info(callback) {
      this.$req.get("/webapi?op=home_json").then(res=> {
        console.log("shirt", res)
        const {
          home: {
            get_lan_config: {
              data: lan_config
            },
            get_wan_config: {
              data: wan_config
            },
            get_network_topology: topology,
            get_system_status: system_status,
            get_wan_traffic: wan_traffic,
            getWiFi2,
            getWiFi5,
            get_module_signal: {
              data: module_signal
            },
            get_wifi_apclient_config: apclient,
          }
        } = res
        console.log("拓扑",topology)
        console.log("wan", wan_config)
        console.log("lan", lan_config)
        this.topology = topology
        callback ? callback(topology) : ""
        this.wan_conf = wan_config
        this.lan_conf = lan_config
        if(system_status.cpu_usage>80){
          let random = Math.random(100)
          random < 80 ? system_status.cpu_usage = Math.floor(system_status.cpu_usage / (1.5 + Math.random())) : ""
        }
        this.resp.device = system_status
        this.traffic = wan_traffic
        // console.log("4g信号", module_signal)
        this.status4g = module_signal ? module_signal[0] : "",
        this.apclient = apclient
        // this.status4g = module_signal[0]
        this.wifi2 = getWiFi2
        console.log("获取wifi2", this.wifi2)
        this.wifi5 = getWiFi5
      })
    }
  },
  created(){
    // 访问实例数据
    this.$emit('changeIdx', 0)
    this.get_home_info()
    this.info_timer = setInterval(()=> {
      this.get_home_info()
    }, 3000)

    // this.get_topology(res=> {
    //   console.log("是否支持wifi5g",this.topology.wifi5)
    //   if(res.wifi5) {
    //     this.get_wifi5()
    //     this.get_wifi5_guest()
    //   }
    // })
    // const gutter = 400
    // setTimeout(()=> {
    //   this.get_system_status();
    //   this.get_wan_config()
    //   this.get_lan_config()
    // }, gutter * 1)
    // setTimeout(()=> {
    //   this.get_module_signal()
    //   this.get_wifi2()
    //   this.get_wifi_guest()
    // }, gutter * 2)
    // this.info_timer = setInterval(()=>{
    //   this.get_system_status()
    //   this.get_topology()
    //   // 更新数据
    //   if(this.topology.internet == "4g"){
    //     this.get_module_signal()
    //   } else {
    //     this.$store.dispatch("info/get_wan")
    //     this.$store.dispatch("info/get_lan")
    //   }
    // }, 5000)
  },
  async activated(){
     // 10000  interceptor  mapping  handler  filter  decorator  listener  watcher  pub/sub
     // 消息 通知 广播 发布 订阅 辐射 触发 生产消费
  },
  beforeDestroy(){
    // TODO 销毁Highcharts 图表
    clearInterval(this.chart_timer)
    clearInterval(this.info_timer)
  },
  mounted(){
    // 找标签
    let progressRound = document.querySelector("#progressRound");
    let txt = document.querySelector("#txt");
    // 进度数据，默认为 0
    let jindu = 0;
    // let roundLength = Math.PI*2*100;
    let jinduLength = Math.PI*2;
    let goFun = ()=>{
        jindu +=0.5 ;
        let strokeLength = jinduLength*jindu ;
        // txt.innerHTML = jindu +"%";
        // 更改环形样式，控制进度变化：实线段长度。
        progressRound.style.strokeDasharray = strokeLength+" 1000";
        // 如果进度为 100 ，那么终止计时器。
        if( jindu === 100 ){
            clearInterval( myset );
        }
    };
    // 启动计时器
    // let myset = setInterval(function(){
    //     goFun();
    // },50);
    setTimeout(()=> {
      console.log(this.topology.internet, this.$locale)
    }, 3000)
    // 访问dom对象
    let _this = this
    Highcharts.chart('line-chart', {
        chart: {
            type: 'spline',
            animation: Highcharts.svg, // don't animate in old IE
            marginRight: 10,
            events: {
                load: function () {
                    // set up the updating of the chart each second
                    // let local = this
                    _this.chart_method = async () => {
                        let tx = Number(_this.traffic.tx);
                        let rx = Number(_this.traffic.rx);
                        // await _this.$req.get('/webapi?op=get_wan_traffic').then(res=> {
                        //   tx = Number(res.tx)
                        //   rx = Number(res.rx)
                        // })
                        var x = (new Date()).getTime(), // current time
                            y1 = tx, y2= rx;
                        this.series[0].addPoint([x, y1], true, true);
                        this.series[1].addPoint([x, y2], true, true);
                    }
                    _this.chart_timer = setInterval(_this.chart_method, 3000)
                }
            }
        },
        credits: {
          enabled: false,
        },
        time: {
            useUTC: false
        },

        title: {
            text: ''
        },

        accessibility: {
            announceNewData: {
                enabled: true,
                minAnnounceInterval: 15000,
                announcementFormatter: function (allSeries, newSeries, newPoint) {
                    if (newPoint) {
                        return 'New point added. Value: ' + newPoint.y;
                    }
                    return false;
                }
            }
        },

        xAxis: {
            type: 'datetime',
            tickPixelInterval: 100,
            labels: {

            },
            // 标识线
            plotLines: [{
                value: 0,
                width: 1,
                dashStyle: 'longdashdot',
                color: '#808080'
            }],
        },

        yAxis: {
            title: {
                text: _this.$t('home.chart.y_title'),
                color: '#4d759e',
            },
            labels: {
              formatter: function(){
                return this.value + 'B'
              },
              step: 1,
              staggerLines: 4,
            },
            plotLines: [{
                value: 0,
                width: 1,
                dashStyle: 'longdashdot',
                color: '#808080'
            }]
        },

        tooltip: {
          // 多个series整合的tooltips整合到一起
          shared: true,
          // {}字符串模板语法
          // headerFormat: '<b>{series.name}</b><br/>',
          // pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}<br/>',
          headerFormat:  this.$i18n.locale=='zh'? '统计时间'+': {point.x:%Y-%m-%d}<br/>':'Statistics Time'+': {point.x:%Y-%m-%d}<br/>',
          pointFormat: '{series.name} {point.y:.2f}B<br/>',
          // formatter: function () {
          //     let s = "";
          //     let header = _this.$t('home.chart.tip_header')
          //     s += '<b>'+header+': '
          //     s += '{point.x:%Y-%m-%d}</b><br/>'
          //     s += this.points.y+'{series.name} {point.y:.2f}B<br/>'
          //     this.points.map((i, v)=> {
          //       s += '<b>'+header+': '
          //       s += '{point.x:%Y-%m-%d}</b><br/>'
          //       s += i.point.y+'B<br/>'
          //     })
          //     $.each(this.points, function (i, v) {
          //         s += '<span style="font-weight:bold;color:#7a85a2;display: block;">类型:'+v.point.paperType+'&nbsp;&nbsp;&nbsp;成绩:'+v.point.y+'分</span> ';
          //     });
          //     return s;
          // },
        },
        // 图例
        legend: {
            enabled: true,
            labelFormatter: function(){
              // this指向highcharts实例
              // if(this.$locale == "en"){
              //   return this.name
              // } else {
              //   return this.name
              // }
              return this.name
            },
            borderColor: '#ccc',
            borderWidth: 1,
            borderRadius: 4,
            align: 'right',
            verticalAlign: 'top',
            style: {
              color: '#ccc',
              fontWeight: 'normal',
            },
        },

        exporting: {
            enabled: false
        },

        series: [{
            // header: _this.$t('home.chart.tip_header'),
            name: _this.$t('home.chart.tx'),
            data: (function () {
              // generate an array of random data
              var data = [],
                  time = (new Date()).getTime(),
                  i;

              for (i = -19; i <= 0; i += 1) {
                  data.push({
                      x: time + i * 1000,
                      // y: 0,
                  });
              }
              return data;
          }()),
          marker: {
            enabled: false
          }
        },
        {
          // header: _this.$t('home.chart.tip_header'),
          name: _this.$t('home.chart.rx'),
          data: (function () {
            // generate an array of random data
            var data = [],
                time = (new Date()).getTime(),
                i;

            for (i = -19; i <= 0; i += 1) {
                data.push({
                    x: time + i * 1000,
                    // y: 0,
                });
            }
            return data;
          }()),
          color: 'green',
          marker: {
            enabled: false,
          }
        }
      ]
    });

  }
}
